import { useState } from "react";
import {
  loginByEmailPassword,
  loginByEmailCodeApi,
  getEmailCodeApi,
} from "@/services/api/login";
import { ResponseCode } from "@/types/api-common";
import { LoginUserProfileType, sendCodeParamsType } from "@/types/login";
import CurrentUserIdManager from "@/utils/user-utils";
import { useAuth } from "@/contexts/AuthContext";
import { DEFAULT_AVATAR_URL } from "@/config/default-value";
import { useChatUserActions } from "@/hooks/chat/chat-user";
import * as SecureStore from "expo-secure-store";
import { useUserProfileActions } from "@/hooks/user/user-profile";

/**
 * 自定义登录 hook，用于处理登录相关操作
 */

export const useLogin = () => {
  const [isLoading, setIsLoading] = useState(false);
  const { login: authLogin } = useAuth();
  const { upsertProfile } = useChatUserActions();
  const { setCurrentUserProfile } = useUserProfileActions();

  /**
   * 保存登录凭据到本地存储
   * @param email 用户邮箱
   * @param password 用户密码
   */
  const saveLoginCredentials = (email: string, password?: string) => {
    SecureStore.setItem("lastLoginEmail", email);
    password && SecureStore.setItem("lastLoginPassword", password);
  };

  /**
   * 获取上次登录的凭据
   * @returns {email: string, password: string} 上次登录的邮箱和密码
   */
  const getLastLoginCredentials = () => {
    const email = SecureStore.getItem("lastLoginEmail") || "3085974224@qq.com";
    const password =
      SecureStore.getItem("lastLoginPassword") || "Dcy123456789!";
    return { email, password };
  };

  /**
   * 邮箱密码登录
   * @param email 邮箱
   * @param password 密码
   */
  const loginWithEmailPassword = async (email: string, password: string) => {
    setIsLoading(true);
    try {
      const response = await loginByEmailPassword({
        email: email.trim(),
        password: password.trim(),
      });

      if (response.data.code === ResponseCode.SUCCESS) {
        console.log("登录API返回的用户数据:", response.data.data);
        // 确保用户数据有默认头像
        const userData = response.data.data as LoginUserProfileType;
        console.log("用户昵称:", userData.nickname);
        const userProfile = {
          ...userData,
          avatar: userData.avatar || DEFAULT_AVATAR_URL,
          // 如果昵称是默认的"User"，可以尝试使用邮箱前缀作为昵称
          nickname:
            userData.nickname === "User"
              ? email.split("@")[0]
              : userData.nickname || email.split("@")[0],
        };

        console.log("setCurrentUserProfile = ", setCurrentUserProfile);

                console.log("setCurrentUserProfile = ", setCurrentUserProfile);

        CurrentUserIdManager.setUserId(userProfile.id);
        authLogin();
        // 保存登录凭据
        saveLoginCredentials(email, password);

        return { success: true, data: userData };
      }

      return { success: false, message: response.data.message };
    } catch (error) {
      return { success: false, message: error.message };
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 邮箱验证码登录
   * @param email 邮箱
   * @param code 验证码
   */
  const loginWithEmailCode = async (email: string, code: string) => {
    setIsLoading(true);
    try {
      const response = await loginByEmailCodeApi({
        email: email.trim(),
        code: code.trim(),
      });

      if (response.data.code === ResponseCode.SUCCESS) {
        console.log("验证码登录API返回的用户数据:", response.data.data);
        // 确保用户数据有默认头像
        const userData = response.data.data as LoginUserProfileType;
        console.log("用户昵称:", userData.nickname);
        const userProfile = {
          ...userData,
          avatar: userData.avatar || DEFAULT_AVATAR_URL,
          // 如果昵称是默认的"User"，可以尝试使用邮箱前缀作为昵称
          nickname:
            userData.nickname === "User"
              ? email.split("@")[0]
              : userData.nickname || email.split("@")[0],
        };

        // 直接更新 Zustand store
        setCurrentUserProfile(userProfile);

        // 更新sqlite数据
        await upsertProfile({
          id: userProfile.id,
          name: userProfile.nickname,
          avatar: userProfile.avatar,
          updateTime: userProfile.updateTime,
        });
        CurrentUserIdManager.setUserId(userProfile.id);
        authLogin();
        // 保存登录凭据
        saveLoginCredentials(email);

        return { success: true, data: userData };
      }

      return { success: false, message: response.data.message };
    } catch (error) {
      return { success: false, message: error.message };
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 发送邮箱验证码
   * @param email 邮箱
   */
  const sendEmailCode = async (email: string) => {
    setIsLoading(true);
    try {
      const result = await getEmailCodeApi({
        email: email.trim(),
        type: 0,
      } as sendCodeParamsType);

      if (result.data.code === ResponseCode.SUCCESS) {
        return { success: true, message: `已发送至 ${email.trim()}` };
      }
      return { success: false, message: result.data.message };
    } catch (error) {
      return { success: false, message: error.message };
    } finally {
      setIsLoading(false);
    }
  };

  // 返回登录状态和操作方法
  return {
    isLoading,
    saveLoginCredentials,
    getLastLoginCredentials,
    loginWithEmailPassword,
    loginWithEmailCode,
    sendEmailCode,
  };
};
